@*
    生产退料管理添加/编辑页面
*@
@{
    ViewData["Title"] = "生产退料管理";
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>@ViewData["Title"]</title>
    <link href="~/layui/css/layui.css" rel="stylesheet" />
    <style>
        .form-container {
            padding: 20px;
            max-width: 800px;
            margin: 0 auto;
        }
        .required {
            color: red;
        }
        .detail-section {
            margin-top: 30px;
            border-top: 1px solid #e6e6e6;
            padding-top: 20px;
        }
        .detail-title {
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 15px;
        }
    </style>
</head>
<body>
    @Html.AntiForgeryToken()
    <div class="layui-fluid">
        <div class="layui-card">
            <div class="layui-card-header">
                <span id="pageTitle">新增生产退料</span>
            </div>
            <div class="layui-card-body">
                <div class="form-container">
                    <form class="layui-form" lay-filter="productionReturnForm">
                        <input type="hidden" name="id" id="productionReturnId">
                        
                        <div class="layui-row">
                            <div class="layui-col-md6">
                                <div class="layui-form-item">
                                    <label class="layui-form-label"><span class="required">*</span>退料单编号</label>
                                    <div class="layui-input-block">
                                        <input type="text" name="returnCode" readonly class="layui-input">
                                    </div>
                                </div>
                            </div>
                            <div class="layui-col-md6">
                                <div class="layui-form-item">
                                    <label class="layui-form-label"><span class="required">*</span>退料单名称</label>
                                    <div class="layui-input-block">
                                        <input type="text" name="returnName" lay-verify="required|returnName" placeholder="请输入退料单名称" class="layui-input">
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="layui-row">
                            <div class="layui-col-md6">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">生产工单</label>
                                    <div class="layui-input-block">
                                        <div class="layui-input-group">
                                            <input type="text" name="workOrder" placeholder="请选择生产工单" class="layui-input" readonly>
                                            <div class="layui-input-suffix">
                                                <button type="button" class="layui-btn layui-btn-primary" id="selectWorkOrderBtn">
                                                    <i class="layui-icon layui-icon-search"></i>
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="layui-col-md6">
                                <div class="layui-form-item">
                                    <label class="layui-form-label"><span class="required">*</span>接收仓库</label>
                                    <div class="layui-input-block">
                                        <select name="warehouseId" lay-verify="required" lay-search="">
                                            <option value="">请选择仓库</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="layui-row">
                            <div class="layui-col-md6">
                                <div class="layui-form-item">
                                    <label class="layui-form-label"><span class="required">*</span>退料日期</label>
                                    <div class="layui-input-block">
                                        <input type="text" name="returnDate" lay-verify="required" class="layui-input" id="returnDatePicker">
                                    </div>
                                </div>
                            </div>
                            <div class="layui-col-md6">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">状态</label>
                                    <div class="layui-input-block">
                                        <input type="text" name="statusText" readonly class="layui-input" value="草稿">
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="layui-form-item">
                            <label class="layui-form-label">备注</label>
                            <div class="layui-input-block">
                                <textarea name="remark" placeholder="请输入备注" class="layui-textarea" maxlength="500"></textarea>
                            </div>
                        </div>
                        
                        <div class="layui-form-item" style="text-align: center; margin-top: 30px;">
                            <button type="button" class="layui-btn" lay-submit lay-filter="submitForm">保存</button>
                            <button type="button" class="layui-btn layui-btn-primary" id="cancelBtn">取消</button>
                        </div>
                    </form>
                    
                    <!-- 退料明细部分 -->
                    <div class="detail-section" id="detailSection" style="display: none;">
                        <div class="detail-title">退料明细</div>
                        <div class="layui-btn-group" style="margin-bottom: 10px;">
                            <button class="layui-btn layui-btn-sm" id="addDetailBtn">
                                <i class="layui-icon layui-icon-add-1"></i> 添加物料
                            </button>
                        </div>
                        <table id="detailTable" lay-filter="detailTable"></table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="~/layui/layui.js"></script>
    <script>
        layui.use(['form', 'layer', 'laydate', 'table'], function () {
            var form = layui.form;
            var layer = layui.layer;
            var laydate = layui.laydate;
            var table = layui.table;
            var $ = layui.jquery;
            
            var isEdit = false;
            var returnData = null;
            var returnId = null;

            // 获取URL参数
            function getUrlParam(name) {
                var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
                var r = window.location.search.substr(1).match(reg);
                if (r != null) return unescape(r[2]);
                return null;
            }

            // 初始化页面
            function initPage() {
                var id = getUrlParam('id');
                if (id) {
                    isEdit = true;
                    returnId = id;
                    $('#pageTitle').text('编辑生产退料');
                    $('#detailSection').show();
                    loadReturnData(id);
                    loadReturnDetails(id);
                } else {
                    // 新增时生成编号
                    generateReturnCode();
                    // 设置默认退料日期
                    $('input[name="returnDate"]').val(new Date().toLocaleDateString());
                }
                
                // 加载仓库选择列表
                loadWarehouses();
            }

            // 初始化日期选择器
            laydate.render({
                elem: '#returnDatePicker',
                type: 'date'
            });

            // 加载生产退料数据
            function loadReturnData(id) {
                var loadIndex = layer.load();
                $.ajax({
                    url: '/ProductionReturn/GetProductionReturn',
                    type: 'GET',
                    data: { id: id },
                    success: function (res) {
                        layer.close(loadIndex);
                        if (res.success) {
                            returnData = res.data;
                            bindFormData(returnData);
                        } else {
                            layer.msg('获取退料数据失败: ' + res.message);
                        }
                    },
                    error: function (xhr) {
                        layer.close(loadIndex);
                        console.error('获取退料数据错误:', xhr);
                        layer.msg('服务器错误: ' + (xhr.responseJSON && xhr.responseJSON.message ? xhr.responseJSON.message : xhr.statusText));
                    }
                });
            }

            // 绑定表单数据
            function bindFormData(data) {
                // 处理日期格式
                if (data.returnDate) {
                    data.returnDate = new Date(data.returnDate).toLocaleDateString();
                }
                
                // 先设置表单值
                form.val('productionReturnForm', data);
                
                // 重新渲染表单组件
                setTimeout(function() {
                    form.render();
                }, 100);
            }

            // 生成退料单编号
            function generateReturnCode() {
                $.ajax({
                    url: '/ProductionReturn/GenerateReturnCode',
                    type: 'GET',
                    success: function(res) {
                        if (res.success) {
                            $('input[name="returnCode"]').val(res.data);
                        }
                    },
                    error: function(xhr) {
                        console.error('获取编号请求错误:', xhr);
                    }
                });
            }

            // 加载仓库选择列表
            function loadWarehouses() {
                $.ajax({
                    url: '/ProductionReturn/GetWarehousesForSelect',
                    type: 'GET',
                    success: function (res) {
                        if (res.success) {
                            var options = '<option value="">请选择仓库</option>';
                            res.data.forEach(function(item) {
                                var selected = returnData && returnData.warehouseId == item.id ? 'selected' : '';
                                options += `<option value="${item.id}" ${selected}>${item.warehouseName}</option>`;
                            });
                            $('select[name="warehouseId"]').html(options);
                            form.render('select');
                        }
                    },
                    error: function(xhr) {
                        console.error('获取仓库列表错误:', xhr);
                    }
                });
            }

            // 加载退料明细表格
            function loadReturnDetails(returnId) {
                table.render({
                    elem: '#detailTable',
                    url: '/ProductionReturn/GetReturnDetails',
                    method: 'POST',
                    where: {returnId: returnId},
                    page: false,
                    cols: [[
                        {field: 'materialCode', title: '物料编码', width: 120},
                        {field: 'materialName', title: '物料名称', width: 150},
                        {field: 'num', title: '退料数量', width: 100},
                        {field: 'size', title: '规格尺寸', width: 120},
                        {field: 'unit', title: '单位', width: 80},
                        {field: 'batch', title: '批次', width: 100},
                        {field: 'warehouseName', title: '仓库', width: 100},
                        {title: '操作', width: 100, align: 'center', templet: function(d) {
                            return '<a class="layui-btn layui-btn-danger layui-btn-xs" onclick="deleteReturnDetail(' + d.id + ')">删除</a>';
                        }}
                    ]],
                    response: {
                        statusName: 'code',
                        statusCode: 0,
                        msgName: 'msg',
                        countName: 'count',
                        dataName: 'data'
                    }
                });
            }

            // 自定义验证规则
            form.verify({
                returnName: function(value) {
                    if (!value) {
                        return '退料单名称不能为空';
                    }
                    if (value.length > 100) {
                        return '退料单名称长度不能超过100个字符';
                    }
                }
            });

            // 表单提交
            form.on('submit(submitForm)', function (formData) {
                var loadIndex = layer.load();
                var url, postData;
                
                postData = formData.field;
                
                if (isEdit) {
                    url = '/ProductionReturn/UpdateProductionReturn';
                    postData.id = returnData.id;
                } else {
                    url = '/ProductionReturn/CreateProductionReturn';
                    delete postData.id;
                }
                
                // 转换数字字段
                if (postData.warehouseId) {
                    postData.warehouseId = parseInt(postData.warehouseId);
                }
                if (isEdit) {
                    postData.id = parseInt(postData.id);
                }

                console.log("提交数据:", url, postData);

                $.ajax({
                    url: url,
                    type: 'POST',
                    data: {
                        ...postData,
                        __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val()
                    },
                    success: function (res) {
                        layer.close(loadIndex);
                        if (res.success) {
                            layer.msg('操作成功', {
                                icon: 1,
                                time: 2000
                            }, function() {
                                if (!isEdit) {
                                    // 新增成功后转为编辑模式
                                    isEdit = true;
                                    returnId = res.data.id;
                                    returnData = res.data;
                                    $('#pageTitle').text('编辑生产退料');
                                    $('#detailSection').show();
                                    loadReturnDetails(returnId);
                                } else {
                                    // 返回列表页面或关闭窗口
                                    if (window.parent && window.parent.layer) {
                                        window.parent.layer.closeAll();
                                        if (window.parent.layui && window.parent.layui.table) {
                                            window.parent.layui.table.reload('returnTable');
                                        }
                                    } else {
                                        window.location.href = '/ProductionReturn/Index';
                                    }
                                }
                            });
                        } else {
                            layer.msg('操作失败: ' + res.message);
                        }
                    },
                    error: function (xhr) {
                        console.error('提交请求错误:', xhr);
                        layer.close(loadIndex);
                        layer.msg('服务器错误: ' + (xhr.responseJSON && xhr.responseJSON.message ? xhr.responseJSON.message : xhr.statusText));
                    }
                });
                return false;
            });

            // 取消按钮
            $('#cancelBtn').on('click', function () {
                if (window.parent && window.parent.layer) {
                    window.parent.layer.closeAll();
                } else {
                    window.location.href = '/ProductionReturn/Index';
                }
            });

            // 添加明细按钮
            $('#addDetailBtn').on('click', function() {
                if (!returnId) {
                    layer.msg('请先保存退料单基本信息');
                    return;
                }
                openMaterialSelectDialog();
            });

            // 生产工单选择按钮
            $('#selectWorkOrderBtn').on('click', function() {
                openWorkOrderSelectDialog();
            });

            // 打开物料选择对话框
            function openMaterialSelectDialog() {
                var materialDialogIndex = layer.open({
                    type: 1,
                    title: '选择物料',
                    content: `
                        <div style="padding: 20px;">
                            <div class="layui-form layui-form-pane">
                                <div class="layui-form-item">
                                    <div class="layui-inline">
                                        <label class="layui-form-label">关键字</label>
                                        <div class="layui-input-inline">
                                            <input type="text" id="materialKeyword" placeholder="物料编码/名称/规格" class="layui-input">
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <button class="layui-btn" onclick="searchMaterials()">搜索</button>
                                    </div>
                                </div>
                            </div>
                            <table id="materialSelectTable" lay-filter="materialSelectTable"></table>
                            <div style="margin-top: 15px; text-align: center;">
                                <button class="layui-btn" onclick="confirmSelectMaterial()">确定</button>
                                <button class="layui-btn layui-btn-primary" onclick="closeMaterialDialog()">取消</button>
                            </div>
                        </div>
                    `,
                    area: ['900px', '600px'],
                    success: function() {
                        loadMaterialSelectTable();
                    }
                });

                function loadMaterialSelectTable() {
                    table.render({
                        elem: '#materialSelectTable',
                        url: '/ProductionReturn/GetMaterialsForReturn',
                        method: 'GET',
                        page: true,
                        cols: [[
                            {type: 'radio', width: 60},
                            {field: 'materielCode', title: '物料编码', width: 120},
                            {field: 'materielName', title: '物料名称', width: 150},
                            {field: 'specifications', title: '规格型号', width: 120},
                            {field: 'unitsId', title: '单位', width: 80},
                            {field: 'stockQuantity', title: '库存数量', width: 100}
                        ]],
                        request: {
                            pageName: 'page',
                            limitName: 'maxResultCount'
                        },
                        response: {
                            statusName: 'code',
                            statusCode: 0,
                            msgName: 'msg',
                            countName: 'count',
                            dataName: 'data'
                        },
                        before: function(req) {
                            if (req.page) {
                                req.skipCount = (req.page - 1) * (req.maxResultCount || 10);
                                delete req.page;
                            }
                            return req;
                        }
                    });
                }

                window.searchMaterials = function() {
                    var keyword = $('#materialKeyword').val();
                    table.reload('materialSelectTable', {
                        where: {keyword: keyword},
                        page: {curr: 1}
                    });
                };

                window.confirmSelectMaterial = function() {
                    var checkStatus = table.checkStatus('materialSelectTable');
                    var data = checkStatus.data;
                    
                    if (data.length === 0) {
                        layer.msg('请选择物料');
                        return;
                    }

                    var selectedMaterial = data[0];
                    layer.close(materialDialogIndex);
                    openMaterialDetailDialog(selectedMaterial);
                };

                window.closeMaterialDialog = function() {
                    layer.close(materialDialogIndex);
                };
            }

            // 打开物料详情输入对话框
            function openMaterialDetailDialog(material) {
                // 获取仓库列表
                $.get('/ProductionReturn/GetWarehousesForSelect', function(res) {
                    if (res.success) {
                        var warehouseOptions = '<option value="">请选择仓库</option>';
                        res.data.forEach(function(item) {
                            warehouseOptions += `<option value="${item.id}">${item.warehouseName}</option>`;
                        });

                        var detailDialogIndex = layer.open({
                            type: 1,
                            title: '添加退料明细',
                            content: `
                                <form class="layui-form" style="padding: 20px;">
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">物料编码</label>
                                        <div class="layui-input-block">
                                            <input type="text" readonly class="layui-input" value="${material.materielCode}">
                                        </div>
                                    </div>
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">物料名称</label>
                                        <div class="layui-input-block">
                                            <input type="text" readonly class="layui-input" value="${material.materielName}">
                                        </div>
                                    </div>
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">规格型号</label>
                                        <div class="layui-input-block">
                                            <input type="text" name="size" class="layui-input" value="${material.specifications || ''}">
                                        </div>
                                    </div>
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">单位</label>
                                        <div class="layui-input-block">
                                            <input type="text" readonly class="layui-input" value="${material.unitsId}">
                                        </div>
                                    </div>
                                    <div class="layui-form-item">
                                        <label class="layui-form-label"><span style="color: red;">*</span>退料数量</label>
                                        <div class="layui-input-block">
                                            <input type="number" name="num" required lay-verify="required|number" min="1" class="layui-input">
                                        </div>
                                    </div>
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">批次</label>
                                        <div class="layui-input-block">
                                            <input type="text" name="batch" class="layui-input">
                                        </div>
                                    </div>
                                    <div class="layui-form-item">
                                        <label class="layui-form-label"><span style="color: red;">*</span>仓库</label>
                                        <div class="layui-input-block">
                                            <select name="warehouseId" required lay-verify="required">
                                                ${warehouseOptions}
                                            </select>
                                        </div>
                                    </div>
                                    <div class="layui-form-item">
                                        <div class="layui-input-block">
                                            <button class="layui-btn" lay-submit lay-filter="submitDetail">保存</button>
                                            <button type="button" class="layui-btn layui-btn-primary" onclick="layer.close(${detailDialogIndex})">取消</button>
                                        </div>
                                    </div>
                                </form>
                            `,
                            area: ['500px', '600px'],
                            success: function() {
                                form.render();

                                form.on('submit(submitDetail)', function(formData) {
                                    var warehouseId = formData.field.warehouseId;
                                    var warehouseName = $('select[name="warehouseId"] option:selected').text();

                                    var detailData = {
                                        productionReturnId: returnId,
                                        materialCode: material.materielCode,
                                        materialName: material.materielName,
                                        size: formData.field.size,
                                        unit: material.unitsId,
                                        num: parseInt(formData.field.num),
                                        batch: formData.field.batch,
                                        warehouseId: parseInt(warehouseId),
                                        warehouseName: warehouseName
                                    };

                                    $.post('/ProductionReturn/CreateReturnDetail', detailData, function(res) {
                                        if (res.success) {
                                            layer.msg('添加成功');
                                            layer.close(detailDialogIndex);
                                            table.reload('detailTable');
                                        } else {
                                            layer.msg('添加失败：' + res.message);
                                        }
                                    });
                                    return false;
                                });
                            }
                        });
                    }
                });
            }

            // 打开生产工单选择对话框
            function openWorkOrderSelectDialog() {
                layer.open({
                    type: 1,
                    title: '选择生产工单',
                    area: ['900px', '600px'],
                    content: `
                        <div style="padding: 20px;">
                            <div class="layui-form layui-form-pane">
                                <div class="layui-form-item">
                                    <div class="layui-inline">
                                        <label class="layui-form-label">关键字</label>
                                        <div class="layui-input-inline">
                                            <input type="text" id="workOrderKeyword" placeholder="工单编号、工单名称、产品编码、产品名称" class="layui-input">
                                        </div>
                                    </div>
                                    <div class="layui-inline">
                                        <button class="layui-btn" onclick="searchWorkOrders()">搜索</button>
                                    </div>
                                </div>
                            </div>
                            <table id="workOrderSelectTable" lay-filter="workOrderSelectTable"></table>
                        </div>
                    `,
                    success: function(layero, index) {
                        initWorkOrderSelectTable();

                        window.searchWorkOrders = function() {
                            var keyword = $('#workOrderKeyword').val();
                            table.reload('workOrderSelectTable', {
                                where: {keyword: keyword},
                                page: {curr: 1}
                            });
                        };

                        // 监听工单选择
                        table.on('tool(workOrderSelectTable)', function(obj) {
                            var data = obj.data;
                            if (obj.event === 'select') {
                                $('input[name="workOrder"]').val(data.orderCode);
                                layer.close(index);
                                layer.msg('已选择生产工单：' + data.orderCode);
                            }
                        });
                    }
                });
            }

            // 初始化生产工单选择表格
            function initWorkOrderSelectTable() {
                table.render({
                    elem: '#workOrderSelectTable',
                    url: '/ProductionReturn/GetWorkOrdersForSelect',
                    method: 'GET',
                    page: true,
                    cols: [[
                        { field: 'orderCode', title: '工单编号', width: 120 },
                        { field: 'orderName', title: '工单名称', width: 150 },
                        { field: 'productCode', title: '产品编码', width: 120 },
                        { field: 'productName', title: '产品名称', width: 150 },
                        { field: 'specification', title: '规格', width: 120 },
                        { field: 'planQuantity', title: '计划数量', width: 100 },
                        { field: 'status', title: '状态', width: 80 },
                        { title: '操作', width: 100, toolbar: '<div><button class="layui-btn layui-btn-xs" lay-event="select">选择</button></div>' }
                    ]],
                    request: {
                        pageName: 'page',
                        limitName: 'maxResultCount'
                    },
                    response: {
                        statusName: 'code',
                        statusCode: 0,
                        msgName: 'msg',
                        countName: 'count',
                        dataName: 'data'
                    },
                    before: function(req) {
                        if (req.page) {
                            req.skipCount = (req.page - 1) * (req.maxResultCount || 10);
                            delete req.page;
                        }
                        return req;
                    }
                });
            }

            // 删除退料明细（全局函数）
            window.deleteReturnDetail = function(detailId) {
                layer.confirm('确定删除这条退料明细吗？', function(index){
                    $.post('/ProductionReturn/DeleteReturnDetail', {detailId: detailId}, function(res){
                        if(res.success){
                            layer.msg('删除成功');
                            table.reload('detailTable');
                        } else {
                            layer.msg('删除失败：' + res.message);
                        }
                    });
                    layer.close(index);
                });
            };

            // 保存并确认（全局函数，供父窗口调用）
            window.saveAndConfirm = function(callback) {
                // 先验证表单
                var formData = form.val('productionReturnForm');
                if (!formData.returnName) {
                    layer.msg('请输入退料单名称');
                    return;
                }
                if (!formData.warehouseId) {
                    layer.msg('请选择接收仓库');
                    return;
                }
                if (!formData.returnDate) {
                    layer.msg('请选择退料日期');
                    return;
                }

                var loadIndex = layer.load();
                var postData = formData;
                
                // 设置状态为已确认
                postData.status = '已确认';
                postData.statusText = '已确认';
                
                if (isEdit) {
                    postData.id = returnData.id;
                }
                
                // 转换数字字段
                if (postData.warehouseId) {
                    postData.warehouseId = parseInt(postData.warehouseId);
                }
                if (isEdit) {
                    postData.id = parseInt(postData.id);
                }

                var url = isEdit ? '/ProductionReturn/UpdateProductionReturn' : '/ProductionReturn/CreateProductionReturn';
                
                $.ajax({
                    url: url,
                    type: 'POST',
                    data: {
                        ...postData,
                        __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val()
                    },
                    success: function (res) {
                        layer.close(loadIndex);
                        if (res.success) {
                            if (callback) {
                                callback();
                            }
                        } else {
                            layer.msg('确认失败: ' + res.message);
                        }
                    },
                    error: function (xhr) {
                        console.error('确认请求错误:', xhr);
                        layer.close(loadIndex);
                        layer.msg('服务器错误: ' + (xhr.responseJSON && xhr.responseJSON.message ? xhr.responseJSON.message : xhr.statusText));
                    }
                });
            };

            // 初始化页面
            initPage();
        });
    </script>
</body>
</html> 